const { v4: uuidv4 } = require('uuid');
const { db } = require('../config/database');

/**
 * 添加批注
 */
const addAnnotation = (req, res) => {
    const { versionId } = req.params;
    const { rowIndex, columnName, annotationType, annotationData, createdBy } = req.body;

    const annotationId = uuidv4();
    
    db.run(
        `INSERT INTO annotations (id, version_id, row_index, column_name, annotation_type, annotation_data, created_by)
         VALUES (?, ?, ?, ?, ?, ?, ?)`,
        [annotationId, versionId, rowIndex, columnName, annotationType, JSON.stringify(annotationData), createdBy],
        function(err) {
            if (err) {
                console.error(err);
                return res.status(500).json({ error: '添加批注失败' });
            }
            
            res.json({ 
                success: true, 
                annotationId,
                message: '批注添加成功' 
            });
        }
    );
};

/**
 * 获取版本的所有批注
 */
const getAnnotations = (req, res) => {
    const { versionId } = req.params;
    
    db.all(
        'SELECT * FROM annotations WHERE version_id = ? ORDER BY created_at DESC',
        [versionId],
        (err, annotations) => {
            if (err) {
                console.error(err);
                return res.status(500).json({ error: '获取批注失败' });
            }
            
            res.json(annotations);
        }
    );
};

/**
 * 删除批注
 */
const deleteAnnotation = (req, res) => {
    const { annotationId } = req.params;
    
    db.run(
        'DELETE FROM annotations WHERE id = ?',
        [annotationId],
        function(err) {
            if (err) {
                console.error(err);
                return res.status(500).json({ error: '删除批注失败' });
            }
            
            if (this.changes === 0) {
                return res.status(404).json({ error: '批注不存在' });
            }
            
            res.json({ 
                success: true,
                message: '批注删除成功' 
            });
        }
    );
};

module.exports = {
    addAnnotation,
    getAnnotations,
    deleteAnnotation
};